var express = require('express');
var router = express.Router();
var mongoose = require('../models/db');
var dgModel = require('../models/dongguModel');
var sd = require('silly-datetime');
var time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
var request=require('request');

/*保存景点*/
router.post('/save', function (req, res, next) {

    let dg_title = req.body.dg_title;
    let dg_cover = req.body.dg_cover;
    let dg_desc = req.body.dg_desc;
    let dg_recom = req.body.dg_recom;
    let dg_type = req.body.dg_type;
    const dgDB = new dgModel({
        'dg_title': dg_title || '',
        "dg_cover": dg_cover|| '',
        "dg_desc": dg_desc|| '',
        "dg_recom":dg_recom|| false,
        "dg_type":dg_type|| '景点',
        "dg_time": time
    });

    dgDB.save(function (err, doc) {
        if (err) {
            res.json({
                success: false,
                msg: err.message
            });
        }
        else {

                res.json({
                    success: true,
                    msg: '保存成功！'
                })

        }
    })
});
//引入Multiparty解析表单
var fs = require('fs');
/*上传封面*/
router.post("/uploadCover", function (req, res,next) {
    let base64Data=req.body.base64Data.replace(/^data:image\/\w+;base64,/, '');
    let binaryData=new Buffer(base64Data,"base64").toString("binary");
    var savePath="views/static/cover/"+Date.now()+".jpg";
    var newPath=savePath.replace('views/','');
    if(!base64Data){
        res.json({
            success: false,
            msg: '上传出错！',
            result: {

            }
        });
    }
    else{
        fs.writeFile(savePath,binaryData,"binary",function(err){

                if (err) {
                    res.json({
                        success: false,
                        msg: err.message,
                        result: ''
                    });
                }
                else {

                    res.json({
                        success: true,
                        msg: '上传成功',
                        result: {
                            dg_cover:newPath,
                        }
                    })
                }
        });
    }
});

//景点列表
router.post('/list', function (req, res, next) {
    let page = req.body.page;
    let limit = req.body.limit;
    let dg_type = req.body.dg_type;
    dgModel.count({"dg_type":dg_type},function (err, count) {
        dgModel
            .find({"dg_type":dg_type})
            .skip(page * limit)
            .limit(parseInt(limit))
            .sort({'_id': -1})
            .exec(function (err, doc) {
                if (err) {
                    res.json({
                        success: false,
                        msg: err.message,
                    });
                }
                else {
                    let newList=[];
                    for(let i=0;i<doc.length;i++){
                        let newData={
                            _id:doc[i]._id,
                            dg_title:doc[i].dg_title,
                            dg_cover:doc[i].dg_cover||''
                        }
                        newList.push(newData)
                    }
                    res.json({
                        success: true,
                        msg: '',
                        result: {
                            count: count,
                            list: newList
                        }
                    })
                }
            })
    });

    //景点详情
    router.post('/info', function (req, res, next) {
        let did = req.body.did;
        dgModel.findOne({'_id': did}, function (err, doc) {
            if (err) {
                res.json({
                    success: false,
                    msg: '',
                    result: {}
                });
            }
            else {

                res.json({
                    success: true,
                    msg: '',
                    result: doc
                })
            }
        })
    });
    //推荐景点
    router.post('/recom', function (req, res, next) {
        let dg_type=req.body.dg_type;
        dgModel.find({'dg_recom': true})
            .where('dg_type').equals(dg_type)
            .exec(function (err, doc) {
            if (err) {
                res.json({
                    success: false,
                    msg: '',
                    result: {}
                });
            }
            else {
                let newList=[];
                var len=0;
                if(doc.length>3){
                    len=3
                }
                else{
                    len=doc.length
                }
                for(let i=0;i<len;i++){
                    let newData={
                        _id:doc[i]._id,
                        dg_title:doc[i].dg_title,
                        dg_cover:doc[i].dg_cover||''
                    }
                    newList.push(newData)
                }
                res.json({
                    success: true,
                    msg: '',
                    result: {
                        list:newList
                    }
                })
            }
        })
    });
});

/*管理员登录*/
router.post('/chekLogin', function (req, res, next) {
    let userName = req.body.userName;
    let userPwd = req.body.userPwd;

    if(userName==='qun' && userPwd==='qun931120'){
        res.json({
            success: true,
            msg: '登录成功！',
            result: {
                userName:userName,
            }
        });
    }
    else{
        res.json({
            success: false,
            msg: '用户名或密码错误！',
            result: {
                userName: ''
            }
        });
    }
});

//删除景点
router.post('/remove', function (req, res, next) {
    let did = req.body.did;
    dgModel.remove({'_id': did}, function (err, doc) {
        if (err) {
            res.json({
                success: false,
                msg: '删除失败！',
                result: ''
            });
        }
        else {

            res.json({
                success: true,
                msg: '删除成功！',
                result: ''
            })
        }
    })
});

//更新景点
router.post('/update', function (req, res, next) {
    let did = req.body.did;
    let dg_title = req.body.dg_title;
    let dg_cover = req.body.dg_cover;
    let dg_desc = req.body.dg_desc;
    let dg_recom = req.body.dg_recom;
    let dg_type = req.body.dg_type;
    let updates = {$set: {
            'dg_title': dg_title || '',
            "dg_cover": dg_cover|| '',
            "dg_desc": dg_desc|| '',
            "dg_recom":dg_recom|| false,
            "dg_type":dg_type || '景点',
            "dg_time": time,
    }}
    dgModel.update({'_id': did},updates, function (err, doc) {
        console.log(err);
        if (err) {
            res.json({
                success: false,
                msg: '修改失败！',
                result: ''
            });
        }
        else {

            res.json({
                success: true,
                msg: '修改成功！',
                result: ''
            })
        }
    })
});

//获取小程序code
router.post('/wxlogin', function (req, res, next) {
    //const Ut = require("../models/utils");
    try {
        console.log(req.body);
        let appId = "wxd19d541793c9c7f1";
        let secret = "1474e267cfa22282af5be5289e918545";
        let { js_code } = req.body;
        let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${secret}&js_code=${js_code}&grant_type=authorization_code`;


        request(url, function (error, response, body) {
            var jsons=JSON.parse(body)
           if(jsons.openid){
               res.json(jsons);
           }
           else{
               res.json({
                   success: false,
                   msg: '获取code失败！',
                   result: ''
               })
           }
        })
    }
    catch (e) {
        res.json({
            success: false,
            msg: '获取code失败！',
            result: ''
        })
    }

})

module.exports = router;
